<template>
  <div id="app">
    <v-touch class="page" @tap="screenTouch($event)">
      <!-- 首页  -->
      <transition name="default">
        <Index v-if="!load || !indexLoad" />
      </transition>
      <!-- 触点反馈 -->
      <!-- 音乐 -->
      <Music />
      <router-view v-if="load && indexLoad"></router-view>
      <Popup v-if="popup.isShow" />
      <PackCard v-if="packCard" />
      <transition name="loadingAnimation">
        <Loading v-if="loading.isShow" />
      </transition>
    </v-touch>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex"
import PackCard from "./components/common/packCard.vue"
import Music from "./components/common/music.vue"
import Index from "./components/common/index.vue"
import Popup from "./components/common/popup.vue"
import Loading from "./components/common/loading.vue"
import Vue from "vue"
export default {
  data() {
    return {
      studyPopShow: false,
      indexLoad: false,
      load: false,
      userData: {},
      imageUrls: []
    }
  },
  components: {
    Music,
    Index,
    PackCard,
    Popup,
    Loading
  },
  created() {
	 this.initData()
  },
  mounted() {
    this.screenFontSize()
    // window.onresize = () => {
    //   this.screenFontSize()
    // }
  },
  methods: {
    //屏幕适配 修改窗口宽高变量
    screenFontSize: function () {
      const scale = parseFloat(getComputedStyle(window.document.documentElement)["font-size"]) / (screen.availHeight / 360 * 16)
      document.getElementsByTagName('html')[0].style.fontSize = screen.availWidth / 48 / scale + 'px'
      this.initWindow({
        windowWidth: document.body.clientWidth,
        windowHeight: document.body.clientHeight,
        mainWidth: $(".page").width(),
        mainHeight: $(".page").height(),
        fontSize: screen.availWidth / 48 / scale
      })
    },
    //点击屏幕小原点 修改当前坐标
    screenTouch: function (event) {
      let roots = document.getElementsByTagName("html")[0].style
      roots.setProperty("--touchX", event.center.x + "px")
      roots.setProperty("--touchY", event.center.y + "px")
    },
    isload: function () {
      this.indexLoad = true
    },
    //获取用户初始数据
    async initData() {
      if (this.variable.isMp) {
        const json = { code: this.variable.CODE }
        const url = "https://activity-back-test.huibenxia.com/"
        const data = await this.$post(url + "weixin/parse-code-to-device-uuid.do", json)
        Vue.prototype.deviceUuid = data.deviceUuid
		}
		console.log(this.deviceUuid);
      const json = {
        deviceUuid: this.deviceUuid,
        deviceWidth: document.body.clientWidth,
        deviceHeight: document.body.clientHeight,
        dpr: window.devicePixelRatio
      }
      const [data, err] = await this.awaitWarp(this.$post(this.api.loadInitData, json))
      if (err) {
        this.setPopup({
          content: "获取数据失败-请检查网络"
        })
      }
      this.userData = data
      if (this.isCdvfile()) this.replaceUrl()
      if (this.variable.isIos) this.replaceWebp()
      this.initUserData()
    },
    //替换url
    replaceUrl: function () {
      this.eachDescendentParameters({
        object: this.userData.user,
        onEach: (map, key, value) => {
          if (typeof value === 'string' && (value.indexOf("nomedia") > -1) && (value.indexOf(".png") > -1 || value.indexOf(".jpg") > -1)) {
            try {
              value = "https://hz-huibenxia.oss-cn-shenzhen.aliyuncs.com" + value.match(/nomedia(\S*)/)[1]
            } catch (error) {
              console.log(error)
            }
            this.imageUrls.push(value)
            map[key] = value
          }
        }
      })
      this.userData.picbooks = this.userData.picbooks.map(item => {
        item.detail.thumbnailUrl = "https://load/.nomedia" + item.detail.thumbnailUrl.match(/com(\S*)/)[1]
        return item
      })
    },
    replaceWebp: function () {
      this.eachDescendentParameters({
        object: this.userData.picbooks,
        onEach: (map, key, value) => {
          if (typeof value === 'string' && (value.indexOf(".png") > -1 || value.indexOf(".jpg") > -1)) {
            try {
              if (value.lastIndexOf("?") > -1) value = value.slice(0, value.lastIndexOf("?"))
            } catch (error) {
              console.log(error)
            }
            this.imageUrls.push(value)
            map[key] = value
          }
        }
      })
    },
    //用户数据初始化
    initUserData: function () {
      this.userData.picbooks = this.userData.picbooks.filter(item=>{
        return item.type !== 'question'
      })
      this.setPicbookList(this.userData.picbooks) //绘本列表初始化
      this.setUserVip(this.userData.userVip) //用户vip信息
      const vipPicbookList = []
      this.userData.picbooks.forEach(item=>{
        for (let i in this.userVip.picbookIdAndCodeMapWithFree){
          if(item.id === parseInt(i)){
            item.vipFreeType = this.userVip.picbookIdAndCodeMapWithFree[i]
            vipPicbookList.push(item)
          }
        }
        this.userVip.picbooksWithCharge.forEach(vItem =>{
          if(item.id === vItem){
            item.vipFreeType = 0
            vipPicbookList.push(item)
          }
        })
      })
      this.setVipPicbookList(vipPicbookList) //用户vip限定绘本
      this.setUserMastery(this.userData.mastery) //用户评测结果
      this.initPack(this.userData) //用户背包初始化
      this.initProduce(this.userData) //用户创作初始化
      this.initUserInformation(this.userData) //用户登录信息初始化
      this.initUserCollect(this.userData) //用户收集的数据初始化
      this.setReadDurationMs(this.userData.readPicbook.readDurationMs) //重复请求间隔
      this.initSeedActivity(this.userData)//种子用户数据收集
      this.preload() //图片资源加载
      this.load = true
    },
    //用户背包初始化
    initPack: function (data) {
      const pack = data.user.userData ? data.user.userData.pack ? data.user.userData.pack : [] : []
      this.setPack(pack)
    },
    //用户创作初始化
    initProduce: async function (data) {
      const produces = data.user.userData ? data.user.userData.produces ? data.user.userData.produces : {} : {}
      const userProduceList = data.user.userData ? data.user.userData.userProduceList ? data.user.userData.userProduceList : [] : []
      const collectionIdList = data.user.userData ? data.user.userData.collectionIdList ? data.user.userData.collectionIdList : [] : []
      this.setProduce(produces)
      this.setUserProduceList(userProduceList)
      this.setCollectionIdList(collectionIdList)
      const [data2, err] = await this.awaitWarp(this.$post(this.api.recPicbookList))
      data2.picbooks.map(item => {
        item.content = JSON.parse(item.content)
        return item
      })
      this.setCommunityList(data2.picbooks)
    },
    //用户登录信息初始化
    initUserInformation: function (data) {
      this.setUserInformation({
        phoneNumber: data.userProfile.phoneNumber,
        detail: data.userProfile.detail,
        isWechat: data.isWeixinBound
      })
    },
    //用户收集的数据初始化
    initUserCollect: function (data) {
      const resultOption = {
        imagery: [],
        role: []
      }
      const userCollect = data.user.userData ? data.user.userData.userCollect ? data.user.userData.userCollect : resultOption : resultOption
      this.setUserCollect(userCollect)
    },
    //种子用户数据收集
    initSeedActivity: function (data) {
      const seedActivity = data.seedActivity ? data.seedActivity : {}
      this.setSeedActivity(seedActivity)
    },
    /*
      图片缓存
      用户为移动端则缓存收集的意向图
      讲本地图片地址转为http地址再缓存
      防止用户清除数据pack空白
    */
    preload: function () {
      if (this.isCdvfile()) {
        document.addEventListener("deviceready", () => {
          this.LoadFeature.loadFiles({
            fileUrls: this.imageUrls,
            onProcess: loadedCount => { }, // 每上传一个文件,触发此方法一次
            onAllLoad: function (fileUrlAndPathMap) { }, // 当上传完所有文件后，触发此方法
            onError: function () { }
          })
        }, false)
      }
    },
    ...mapActions("mainStatus", ["setPopup", "setReadDurationMs"]),
    ...mapActions("packStatus", ["setPack"]),
    ...mapActions("produceStatus", ["setProduce", "setUserProduceList", "setCollectionIdList", "setCommunityList"]),
    ...mapActions("picbookListStatus", ["setPicbookList","setVipPicbookList"]),
    ...mapActions("personalStatus", ["setUserInformation", "setUserCollect", "setUserMastery","setUserVip"]),
    ...mapActions("seedActivityStatus", ["setSeedActivity"])
  },
  computed: {
    ...mapGetters("mainStatus", {
      popup: "getPopup",
      loading: "getLoading",
    }),
    ...mapGetters("packStatus", {
      packCard: "getPackCard",
      pack: "getPack",
    }),
    ...mapGetters("seedActivityStatus", {
      seedActivity: "getSeedActivity"
    }),
    ...mapGetters("personalStatus",{
      userVip: "getUserVip"
    })
  },
  watch: {
    //更新背包数据
    pack: function (newPack, oldPack) {
      if (oldPack.length > 0) {
        this.userSaveDate("pack", newPack)
      }
    }
  }
}
</script>

<style scoped lang='stylus'>
.page
  position fixed
  width var(--contentWidth)
  height var(--contentHeight)
  transform translate3d(var(--X), var(--Y), 0)
  margin 0 auto
  text-align center
  font-weight 500
  overflow hidden
</style>
